/**
* Author: fulishang
* Create Time  : 2016年8月4日,下午10:02:32
* Modify Time :
* Desc  : 
*/
package com.sam.si.file.boot;

import java.io.File;
import java.io.IOException;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.integration.annotation.Poller;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.file.FileReadingMessageSource;
import org.springframework.integration.file.filters.CompositeFileListFilter;
import org.springframework.messaging.MessageChannel;

import com.sam.si.file.filter.FileFilter;
import com.sam.si.file.processor.FileProcessor;
import com.sam.si.file.transformer.FileTransformer;
import com.sam.si.file.util.Constants;

@SpringBootApplication
public class FileReadDirectoryApplication {

	public static void main(String[] args) throws IOException, InterruptedException {
		SpringApplication.run(FileReadDirectoryApplication.class, args);
	}

	@Bean
	public IntegrationFlow processFileFlow() {
		return IntegrationFlows.from("fileInputChannel").transform(fileTransformer())
				.handle("fileProcessor", "process").get();
	}

	@Bean
	public MessageChannel fileInputChannel() {
		return new DirectChannel();
	}

	@Bean
	@InboundChannelAdapter(value = "fileInputChannel", poller = @Poller(fixedDelay = "5000"))//poll every 5 seconds
	public MessageSource<File> fileReadingMessageSource() {
		CompositeFileListFilter<File> filters = new CompositeFileListFilter<>();
		filters.addFilter(new FileFilter());

		FileReadingMessageSource source = new FileReadingMessageSource();
		source.setAutoCreateDirectory(true);
		source.setDirectory(new File(Constants.ROUTER_FILE_DIRECTORY));
		source.setFilter(filters);

		return source;
	}

	@Bean
	public FileTransformer fileTransformer(){
		return new FileTransformer();
	}

	@Bean
	public FileProcessor fileProcessor() {
		return new FileProcessor();
	}

}